package com.liang.book.service;

import com.liang.book.model.CaptchaProperties;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class CaptchaService {
    private final CaptchaProperties captchaProperties;
    private static  final long  VALID_TIME = 60000;
    @Autowired
    public CaptchaService(CaptchaProperties captchaProperties) {
        this.captchaProperties = captchaProperties;
    }

    public boolean checkCaptcha(String captchaCode, HttpSession session) {
        if (!StringUtils.hasLength(captchaCode)) {
            return false;
        }
        String sessionCode = (String) session.getAttribute(captchaProperties.getSession().getCode());
        Long sessionDate = (Long) session.getAttribute(captchaProperties.getSession().getDate());
        if (captchaCode.equalsIgnoreCase(sessionCode) && sessionDate != null && (System.currentTimeMillis() - sessionDate) < VALID_TIME) {
            // 验证码正确且未过期，可以移除session中的验证码和日期
            session.removeAttribute(captchaProperties.getSession().getCode());
            session.removeAttribute(captchaProperties.getSession().getDate());
            return true;
        }
        return false;
    }
}
